/**
 * Created by fanyaowu on 2016-7-7       .
 */
(function () {
  'use strict';

  angular
    .module('app')
    .service('modalService', modalService)
    .controller('ModalInstanceCtrl', ModalInstanceCtrl);

  function modalService($uibModal, $log) {
    var vm = this;
    vm.open = function (size, templateUrl, params,functions, cb) {
      var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: templateUrl,
        controller: 'ModalInstanceCtrl',
        controllerAs:'modal',
        size: size,
        resolve: {
          params: function () {
            return params;
          },
          functions: function () {
            return functions;
          }
        }
      });

      modalInstance.result.then(function (result) {
        cb(true, result);
      }, function () {
        cb(false);
      });
    };
  }

  function ModalInstanceCtrl($uibModalInstance, params,functions,$log,$rootScope) {

    var vm = this;
    vm.functions = functions;

    if(!params){
      vm.result = {};
    }
    else{
      vm.result = angular.copy(params);//深拷贝，值复制
    }

    var unbind = $rootScope.$on('modalParamChange', function(e,d){

      $log.info(e,d);

      // 遍历属性，赋值所需要的
      for(var o in d){
        vm.result[o] = d[o];
      }
    });

    vm.ok = function () {
      $uibModalInstance.close(vm.result);
    };

    vm.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };
  }
})();
